import os
import dashscope
from datetime import datetime
from typing import List, Optional, Dict

def generate_travel_guide(api_key: str, request_data: Dict) -> Optional[str]:
    """
    Generate English travel guides using Dashscope API
    """
    try:
        # Merge interest tags
        existing = request_data.get('existing_interests', []) or []
        selected = request_data.get('selected_interests', []) or []
        all_interests = list(set(existing + selected))

        # Construct system prompt
        system_prompt = """You are a professional travel planner. Generate a structured travel guide in English with:
1. Markdown formatting
2. Daily itineraries
3. Practical advice and注意事项
4. Must align with specified budget and travel style
5. Use local time and measurement units
6. Include estimated time allocations"""

        # Build user input
        base_info = request_data['base_info']
        user_input = f"""
**Destination**: {base_info['destination']}

**Travel Dates**:
- Departure: {base_info['departure_date'].strftime('%B %d, %Y')}  # 直接使用datetime对象
- Duration: {base_info['duration']}

**Group Composition**: {base_info['group_description']}

**Key Interests**: {", ".join(all_interests) if all_interests else "General exploration"}

**Travel Style**: {request_data['preferences']['style']}

**Special Requirements**: {request_data['preferences'].get('restrictions', 'None')}

**Budget Range**: {request_data['resources']['budget']}

**Accommodation Preference**: {request_data['resources']['accommodation']}

**Transportation Mode**: {request_data['resources']['transportation']}
"""

        # Call API
        response = dashscope.Generation.call(
            model="qwen-max",
            api_key=api_key,
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_input}
            ],
            result_format='message',
            temperature=0.7,
            top_p=0.9,
            seed=1234
        )

        return response.output.choices[0].message.content if response.status_code == 200 else None

    except Exception as e:
        print(f"Error generating travel guide: {str(e)}")
        return None

'''
# Example usage (for testing)
if __name__ == "__main__":
    test_data = {
        "base_info": {
            "destination": "Great Wall of China",
            "departure_date": "2025-05-01T00:00:00",
            "duration": "3 days 2 nights",
            "group_description": "2 adults with 1 child (age 10)"
        },
        "preferences": {
            "style": "Cultural immersion + family-friendly",
            "restrictions": "Need midday break time"
        },
        "resources": {
            "budget": "Mid-range ($150/day)",
            "accommodation": "4-star hotel in Wangfujing area",
            "transportation": "Subway + ride-hailing"
        },
        "selected_interests": ["Imperial history", "Ancient architecture"],
        "existing_interests": ["World Heritage Sites", "Hiking"]
    }

    api_key = os.getenv("DASHSCOPE_API_KEY")
    guide = generate_travel_guide(api_key, test_data)

    if guide:
        print("Successfully generated travel guide:\n")
        print(guide)
    else:
        print("Failed to generate guide")

'''